<script setup>
import { ElMessage } from 'element-plus'
import {useRouter} from "vue-router";
import {useStore} from "vuex";
import {computed, onMounted} from "vue";
import { reactive, ref, watch  } from 'vue'
import { FormItemProps, FormProps } from 'element-plus'
import axios from 'axios'

const store = useStore();
const router = useRouter();
const labelPosition = ref('right');
const itemLabelPosition = ref('right');

let HiddenOrNo = ref(true);

//初始化下标
let finalindex = 0;
const userObj = computed(() => {
  const user = store.state.user;
  // 确保返回的对象始终包含所需的属性
  return {
    ...user,
    consultantLevel: user?.consultantLevel || { consultantLevelName: '暂无等级' },
    consultantName: user?.consultantName || '',
    fullName: user?.fullName || '',
    consultantPhone: user?.consultantPhone || '',
    consultantAddress: user?.consultantAddress || '',
    consultantDesc: user?.consultantDesc || '',
    consultantIntroduction: user?.consultantIntroduction || '',
    consultantGender: user?.consultantGender || '',
    consultantAge: user?.consultantAge || '',
    consultantAvatar: user?.consultantAvatar || ''
  };
});

//==================================
//密码页面的初始值
const passwordPage = reactive({
  oldpassword: '',
  newpassword: '',
  confirmpassword: '',
});
//基本信息页面的初始值
const massagePage = reactive({
  // consultantAvatar: userObj.value.consultantAvatar,
  consultantName: userObj.value.consultantName,
  consultantPhone: userObj.value.consultantPhone,
  consultantAddress: userObj.value.consultantAddress,
  consultantDesc: userObj.value.consultantDesc,
  consultantIntroduction:userObj.value.consultantIntroduction,
  consultantGender: userObj.value.consultantGender, consultantAge: userObj.value.consultantAge,
});
// 自定义格式化函数，将0或1转换为对应的字符串
const formatGenderValue = (value) => {
  return value === 0? '男' : '女';
};
// 新增计算属性，用于将consultantGender的值转换为字符串显示
const genderStr = computed(() => {
  return formatGenderValue(massagePage.consultantGender);
});

//传入一个对象, 如果有这个对象中至少存在一个空字符串,那么就返回true
const hasEmptyString = function (obj) {
  return Object.values(obj).some(value => value === '');
}

//确认修改基本信息
const changeMassage = function () {
  console.log(massagePage.consultantGender)
  // massagePage.consultantGender = genderStr.value;

  if (hasEmptyString(massagePage) || selectedProvince.value === '' || selectedCity.value === ''){
    open2("输入框中不能为空");
  }else{
    let user = sessionStorage.getItem('user');
    user = JSON.parse(user);//将字符串解析为对象
    console.log(user.consultantId)
    axios.put("/consultants", {
      consultantId: user.consultantId,
      consultantName: massagePage.consultantName,
      consultantPhone: massagePage.consultantPhone,
      consultantAddress: selectedProvince.value + selectedCity.value,
      consultantDesc: massagePage.consultantDesc,
      consultantIntroduction:massagePage.consultantIntroduction,
      consultantGender: genderStr.value,
      consultantAge: massagePage.consultantAge,
    }).then((req)=>{
      if (req.data.code === 200){
        user.consultantName = massagePage.consultantName;
        user.consultantPhone = massagePage.consultantPhone;
        user.consultantAddress = selectedProvince.value + selectedCity.value;
        user.consultantDesc = massagePage.consultantDesc;
        user.consultantIntroduction = massagePage.consultantIntroduction;
        user.consultantGender = genderStr.value;
        //同步到vuex
        store.state.user = user;
        //同步到本地存储
        sessionStorage.setItem('user', JSON.stringify(user));
        open1();
      }else{
        open2("修改失败");
      }
    })
        .catch((error)=>{
          console.error(error);
        })
  }
}
//确认修改密码
const changePassword = function () {
  //判断是否有空字符串
  if (hasEmptyString(passwordPage)) {
    open2("输入框中不能为空");
  }else{
    if (passwordPage.oldpassword === userObj.value.consultantPassword){
      if (passwordPage.newpassword === passwordPage.confirmpassword){
        axios.put("/consultants", {
          consultantId: userObj.value.consultantId,
          consultantPassword: passwordPage.confirmpassword,
        }).then((req)=>{
          if (req.data.code === 200){//后端修改成功
            let user = sessionStorage.getItem('user');
            user = JSON.parse(user);//将字符串解析为对象
            user.consultantPassword = passwordPage.confirmpassword;
            store.state.user = user;
            sessionStorage.setItem('user', JSON.stringify(user));
            open1();
            //重置
            passwordPage.oldpassword = "";
            passwordPage.newpassword = "";
            passwordPage.confirmpassword = "";
          }
        }).catch((error)=>{
          console.error(error);
        })
      }else{
        open2("两次输入的密码不一致");
      }
    }else{
      open2("旧密码错误");
    }

  }
}

//密码修改成功/基本信息修改成功
const open1 = () => {
  ElMessage({
    message: '修改成功.',
    type: 'success',
  })
}
//密码修改失败/基本信息修改失败
const open2 = (msg) => {
  ElMessage.error(msg);
}

//点击显示模块事件
let onclicknum = "";
const changeHidden = function (value) {
  if (value !== onclicknum) {
    HiddenOrNo.value = !HiddenOrNo.value;
    onclicknum = value;
  }
}

// 获取所有的省份和城市数据
const provinces = computed(() => store.getters.getProvinceCityData);
const positions = ref([]); // 城市列表
// 当前选中的省份和城市
const selectedProvince = ref('');
const selectedCity = ref('');

// 根据选中的省份获取对应的城市列表
const fetchPositions = () => {
  selectedCity.value = ''  //重置城市
  if (selectedProvince.value) {
    positions.value = store.getters.getCitiesByProvince(selectedProvince.value);
    return;
  }
  positions.value = [];
};

// 定义一个函数来解析地址并分离省份和城市
function parseProvinceAndCity(address) {
  // 定义一个正则表达式来匹配省份和城市
  const regex = /^(.*?省|.*?自治区|.*?直辖市)(.*?市|.*?县|.*?区)$/;
  if (address != undefined && address !== null && address !== ''){
    const match = address.match(regex);
    if (match) {
      const province = match[1]; // 省份部分
      const city = match[2];     // 城市部分
      return { province, city };
    } else {
      // 如果地址格式不符合预期，返回空对象或默认值
      console.warn('地址格式不正确:', address);
      return { province: '', city: '' };
    }
  }

}

const fileInput = ref(null); // 创建一个ref来引用input元素

const changeImg = () => {
  fileInput.value.click(); // 触发input元素的点击事件，弹出文件选择对话框
};
//文件上传
const handleFileUpload = (e) => {
  const file = e.target.files[0]; // 获取用户选择的第一个文件（如果支持多选，可根据需求处理多个文件
    const formData = new FormData();
    formData.append('file', file); // 将文件添加到FormData对象中，假设后端接收的参数名为avatar
    axios.post('/admin/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data' // 设置请求头，用于正确传输文件
      }
    }).then((response) => {
      if (response.data.code === 200) {
          console.log("头像上传成功",response.data.msg)
          let user = sessionStorage.getItem('user');
          user = JSON.parse(user);
          console.log(user.consultantId);
          axios.put("/consultants", {
            consultantId: user.consultantId,
            consultantAvatar: response.data.msg,
          }).then((req)=>{
              if(req.data.code === 200){
                user.consultantAvatar = response.data.msg;
                store.state.user = user;
                sessionStorage.setItem('user', JSON.stringify(user));
                console.log("数据库修改成功")
              }else{
                open2("数据库修改失败");
              }
            })
      } else {
        console.error('头像上传失败：', response.data.msg);
      }
    }).catch((error) => {
      console.error('上传头像请求出错：', error);
    });

};

onMounted(() => {
  // 确保从 sessionStorage 获取的数据有效
  const storedUser = sessionStorage.getItem('user');
  if (storedUser) {
    try {
      const parsedUser = JSON.parse(storedUser);
      store.state.user = parsedUser;
      
      // 设置性别，添加空值检查
      if (parsedUser?.consultantGender !== undefined) {
        massagePage.consultantGender = parsedUser.consultantGender === '男' ? 0 : 1;
      }

      // 解析地址时添加空值检查
      if (parsedUser?.consultantAddress) {
        const { province, city } = parseProvinceAndCity(parsedUser.consultantAddress);
        selectedProvince.value = province;
        selectedCity.value = city;
        if (province) {
          positions.value = store.getters.getCitiesByProvince(province);
        }
      }
    } catch (error) {
      console.error('解析用户数据失败:', error);
      ElMessage.error('获取用户数据失败');
    }
  }
});

</script>


<template>
<div class="userbox">
  <ul>
    <li>个人资料</li>
      <div class="userbox-img" v-if="userObj.consultantAvatar">
        <img @click="changeImg" :src="userObj.consultantAvatar" width="150px" alt="没有图片">
      </div>
      <input type="file" ref="fileInput" @change="handleFileUpload" v-show="false" />
    <li>
      <div>用户名称</div>
      <div>{{userObj.consultantName}}</div>
    </li>
    <li>
      <div>真实姓名</div>
      <div>{{userObj.fullName}}</div>
    </li>
    <li>
      <div>手机号码</div>
      <div>{{userObj.consultantPhone}}</div>
    </li>
    <li>
      <div>咨询师等级</div>
      <div>{{userObj.consultantLevel?.consultantLevelName || '暂无等级'}}</div>
    </li>
    <li>
      <div>地址</div>
      <div>{{userObj.consultantAddress || '暂无地址'}}</div>
    </li>
    <li>
      <div>资质介绍</div>
      <div>{{userObj.consultantDesc || '暂无介绍'}}</div>
    </li>
    <li>
      <div>个人介绍</div>
      <div>{{userObj.consultantIntroduction || '暂无介绍'}}</div>
    </li>
  </ul>
  <div>
    <div class="title-top">
      <div v-once @click="changeHidden('0')">基本信息</div>
      <div v-once @click="changeHidden('1')">修改密码</div>
    </div>
    <div class="title-bottom">
      <ul :class="{isHidden:HiddenOrNo}">
        <li>
          <el-form
              :label-position="labelPosition"
              label-width="auto"
              :model="massagePage"
              style="max-width: 600px"
          >

            <el-form-item label="用户名称" :label-position="itemLabelPosition">
              <el-input v-model="massagePage.consultantName"/>
            </el-form-item>
            <el-form-item label="手机号码" :label-position="itemLabelPosition">
              <el-input v-model="massagePage.consultantPhone"/>
            </el-form-item>

            <!-- 添加控制性别的单选按钮部分 -->
            <el-form-item label="性别" :label-position="itemLabelPosition">
              <el-radio-group v-model="massagePage.consultantGender">
                <el-radio :label="0">男</el-radio>
                <el-radio :label="1">女</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="年龄" :label-position="itemLabelPosition">
              <el-input-number v-model="massagePage.consultantAge" :min="1" :max="150" :step="1"></el-input-number>
            </el-form-item>
<!--            省市二级联动-->
            <el-form-item label="省份" :label-position="itemLabelPosition">
              <el-select v-model="selectedProvince" placeholder="请选择省份"  @change="fetchPositions">
                <el-option
                    v-for="(cities, province) in provinces"
                    :key="province"
                    :value="province"
                    :label="province"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="城市" :label-position="itemLabelPosition">
              <el-select v-model="selectedCity" placeholder="请选择城市">
                <el-option
                    v-for="city in positions"
                    :key="city"
                    :value="city"
                    :label="city"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="资质介绍" :label-position="itemLabelPosition">
              <el-input v-model="massagePage.consultantDesc"/>
            </el-form-item>
            <el-form-item label="个人介绍" :label-position="itemLabelPosition">
              <el-input v-model="massagePage.consultantIntroduction"/>
            </el-form-item>
          </el-form>
        </li>
        <li>
          <el-button type="success" @click="changeMassage">确认修改</el-button>
          <el-button type="danger" @click="router.push('/home/shouye')">返回首页</el-button>
        </li>
      </ul>

      <ul :class="{isHidden:!HiddenOrNo}">
        <li>
          <el-form
              :label-position="labelPosition"
              label-width="auto"
              :model="passwordPage"
              style="max-width: 600px"
          >
            <el-form-item label="旧密码" :label-position="itemLabelPosition">
              <el-input v-model="passwordPage.oldpassword" />
            </el-form-item>
            <el-form-item label="新密码" :label-position="itemLabelPosition">
              <el-input v-model="passwordPage.newpassword" />
            </el-form-item>
            <el-form-item label="确认密码" :label-position="itemLabelPosition">
              <el-input v-model="passwordPage.confirmpassword" />
            </el-form-item>
          </el-form>
        </li>
        <li>
          <el-button type="success" @click="changePassword">确认修改</el-button>
          <el-button type="danger" @click="router.push('/home/shouye')">返回首页</el-button>
        </li>
      </ul>
    </div>
  </div>

</div>
</template>


<style scoped>
.userbox{
  display: flex;
  padding: 10px;
}
.userbox>div{
  width: 800px;
  margin-left: 20px;
  padding: 10px;
  background-color: white;
}
.userbox>ul{
  background-color: white;
  width: 300px;
  padding: 20px;
}

.userbox>ul>li{
  display: flex;
  justify-content: space-between;
  padding: 10px 0;
  border-bottom: 1px solid #ccc;
}
.userbox-img{
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px 0;
}
.userbox-img img{
  cursor: pointer;
  border-radius: 50%;
}
.title-bottom>ul{
  padding: 15px;
  display: none;
}
.isHidden{
  display: block!important;
  background-color: whitesmoke;
  border-radius: 5px;
}
.title-top{
  margin: 10px 0 15px 0;
  display: flex;
}
.title-top>div{
  background-color: lavenderblush;
  border-radius: 5px;
  padding: 5px 20px;
  margin-right: 15px;
}
.title-top>div:hover{
  box-shadow: 0 5px 15px rgba(0,0,0,0.1);
  cursor: pointer;
}
</style>